<template>
  <textarea id="editor" />
</template>
<script lang="ts" setup>
import { onMounted } from 'vue'
import useTokenStore from '@/vendors/store/token'
const tokenStore = useTokenStore()
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  plugins: {
    type: [String, Array],
    default:
      'lists code pagebreak charmap emoticons save preview print image media link powerpaste ' +
      'anchor codesample table wordcount fullscreen help searchreplace hr insertdatetime',
  },
  toolbar: {
    type: [String, Array],
    default:
      '| formatselect fontselect fontsizeselect ' +
      '| undo redo ' +
      '| code bold italic underline strikethrough ' +
      '| alignleft aligncenter alignright alignjustify ' +
      '| outdent indent numlist bullist insertdatetime ' +
      '| table forecolor backcolor removeformat ' +
      '| hr searchreplace pagebreak charmap ' +
      '| fullscreen ' +
      '| link anchor codesample ',
  },
})
const emit = defineEmits(['update:modelValue'])
const imgUploadHandler = (blobInfo: any, success: any, failure: any) => {
  const blob = blobInfo.blob()// 转化为易于理解的file对象
  const file = new File([blob], `image.${blob.type.split('/')[1]}`, {
    type: blob.type
  })
  const xhr = new XMLHttpRequest()
  xhr.withCredentials = false
  xhr.open('POST', import.meta.env.VITE_UPLOAD_IMG_API)
  xhr.setRequestHeader('authorization', tokenStore.getToken)
  xhr.onload = function () {
    if (xhr.status !== 200) {
      // eslint-disable-next-line prefer-promise-reject-errors
      failure('HTTP Error:' + xhr.status)
      return
    }
    const json = JSON.parse(xhr.responseText)
    success(json.data)
  }
  const formData = new FormData()
  formData.append('file', file)
  xhr.send(formData)
}
onMounted(() => {
  (window as any).tinymce.init({
    theme: 'silver',
    toolbar: props.toolbar,
    height: '100%',
    width: '100%',
    selector: '#editor', // css选择器，和jquery的选择器一个道理，建议直接用id
    language: 'zh_CN', // 需要在官网自己下载一个全局的langs包。同时我提供的powerpaste本身自带一个langs包里面含中文，所以可以100%支持中文。
    // plugins: [
    //   'powerpaste' // plugins中，用powerpaste替换原来的paste
    // ],
    plugins: props.plugins,
      external_plugins: {
      powerpaste: '/tinymce/plugins/powerpaste/plugin.min.js',
    },
    branding: false, // 隐藏右下角技术支持
    powerpaste_word_import: 'merge', // 参数可以是propmt, merge, clear，效果自行切换对比
    powerpaste_html_import: 'merge', // propmt, merge, clear
    powerpaste_allow_local_images: true,
    paste_data_images: true,
    images_upload_handler: imgUploadHandler,
    init_instance_callback: (editor: any) => {
      (window as any).tinymce.activeEditor.setContent(props.modelValue)
      editor.on('input', (e: any) => {
        const content = (window as any).tinymce.get(0).getContent()
        emit('update:modelValue', content)
      })
      editor.on('ExecCommand', (e: any) => {
        const content = (window as any).tinymce.activeEditor.getContent()
        emit('update:modelValue', content)
      })
      editor.on('keydown', (e: any) => {
        const content = (window as any).tinymce.activeEditor.getContent()
        emit('update:modelValue', content)
      })
    }
    // tinymce的其他配置参数
  })
})

</script>
